"""
小程序登录
"""
import requests
import json
import logging

from src.api.getToken import ConfigParser

errlog = logging.getLogger("err")


class WeChatLogin:
    def __init__(self):
        self.baseUrl = "https://api.weixin.qq.com/"
        con = ConfigParser()
        app_id = con.get_appid()
        app_secret = con.get_appsecret()
        # app_id = "wx3588c79e5588d6bd"
        # app_secret = "cac006c758deea10927014fc7b290445"
        self.appid = app_id
        self.secret = app_secret
        # self.appid = "wx82fcb5c79c5943c5"
        # self.secret = "656437230280309138e8cdc0"

    def do_login(self, code):

        url = "https://api.weixin.qq.com/cgi-bin/token"

        # app_id = self.appid
        # app_secret = "3258f3e9f4707ef672257d67f4547c83"
        # app_secret = "e0f6835aea2303bc0ff7fde17913706a"
        # app_secret = self.secret

        params = {
            "grant_type": "client_credential",
            "appid": self.appid,
            "secret": self.secret,
            "force_refresh": False
        }
        print("params", params)
        response = requests.post(url, params=params)

        access_token = ""

        if response.status_code == 200:
            print("Request successful!")
            print(response.json())
            res_json = response.json()
            if "access_token" in res_json.keys():
                access_token = res_json["access_token"]
            else:
                return res_json
            print("access_token", access_token)

        else:
            print("Request failed. Status code:", response.status_code)
            print(response.text)

        url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber"

        querystring = {"access_token": access_token}

        # code = "4692bb261b756e64d479c23f952dd7c281dbdee0782682d79be6adf0cbaad767"

        payload = {
            "code": code
        }
        payload = json.dumps(payload)
        headers = {'Content-Type': 'application/json'}
        print("querystring", querystring)
        print("payload", payload)
        response = requests.request("POST", url, data=payload, headers=headers, params=querystring)
        print("response", response.text)

        return eval(response.text)
